Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
chai-as-promised
Advanced tools
The chai-as-promised npm package extends Chai with a fluent language for asserting facts about promises. It allows developers to work with promises in their test assertions in a more natural and expressive way, which is particularly useful when dealing with asynchronous operations in tests.
Asserting a promise is fulfilled
This feature allows you to assert that a promise will be fulfilled. In other words, it checks that the promise will eventually resolve.
expect(promise).to.be.fulfilled;
Asserting a promise is rejected
This feature allows you to assert that a promise will be rejected. This is useful for testing error handling in asynchronous code.
expect(promise).to.be.rejected;
Asserting a promise is rejected with a specific error
With this feature, you can assert that a promise is not only rejected but also that it is rejected with a specific type of error.
expect(promise).to.be.rejectedWith(Error);
Asserting a promise's fulfillment value
This feature allows you to assert what value a promise will be resolved with. The 'eventually' chain is used to wait for the promise to resolve before making the assertion.
expect(promise).to.eventually.equal('foo');
Chaining assertions
chai-as-promised supports chaining assertions, allowing for more complex assertions on the resolved value of a promise.
expect(promise).to.eventually.have.property('bar').that.is.a('string');
Jest is a testing framework that includes its own assertion library and has built-in support for testing asynchronous code. It can handle promises and async/await syntax without the need for additional plugins.
Expect is an assertion library that can be used independently or with Jest. It provides a way to make assertions about promises, similar to chai-as-promised, but it is more tightly integrated with Jest when used in that context.
Chai as Promised extends Chai with a fluent language for asserting facts about promises.
Instead of manually wiring up your expectations to a promise's fulfilled and rejected handlers:
doSomethingAsync().then(
function (result) {
result.should.equal("foo");
done();
},
function (err) {
done(err);
}
);
you can write code that expresses what you really mean:
return doSomethingAsync().should.eventually.equal("foo");
or if you have a testing framework that doesn't allow returning promises to signal asynchronous test completion, then you can use the following workaround:
doSomethingAsync().should.eventually.equal("foo").notify(done);
should
/expect
InterfaceThe most powerful extension provided by Chai as Promised is the eventually
property. With it, you can transform any
existing Chai assertion into one that acts on a promise:
(2 + 2).should.equal(4);
// becomes
return Promise.resolve(2 + 2).should.eventually.equal(4);
expect({ foo: "bar" }).to.have.property("foo");
// becomes
return expect(Promise.resolve({ foo: "bar" })).to.eventually.have.property("foo");
There are also a few promise-specific extensions (with the usual expect
equivalents also available):
return promise.should.be.fulfilled;
return promise.should.eventually.deep.equal("foo");
return promise.should.become("foo"); // same as `.eventually.deep.equal`
return promise.should.be.rejected;
return promise.should.be.rejectedWith(Error); // other variants of Chai's `throw` assertion work too.
assert
InterfaceAs with the should
/expect
interface, Chai as Promised provides an eventually
extender to chai.assert
, allowing
any existing Chai assertion to be used on a promise:
assert.equal(2 + 2, 4, "This had better be true");
// becomes
return assert.eventually.equal(Promise.resolve(2 + 2), 4, "This had better be true, eventually");
And there are, of course, promise-specific extensions:
return assert.isFulfilled(promise, "optional message");
return assert.becomes(promise, "foo", "optional message");
return assert.doesNotBecome(promise, "foo", "optional message");
return assert.isRejected(promise, "optional message");
return assert.isRejected(promise, Error, "optional message");
return assert.isRejected(promise, /error message matcher/, "optional message");
Chai as Promised does not have any intrinsic support for testing promise progress callbacks. The properties you would want to test are probably much better suited to a library like Sinon.JS, perhaps in conjunction with Sinon–Chai:
var progressSpy = sinon.spy();
return promise.then(null, null, progressSpy).then(function () {
progressSpy.should.have.been.calledWith("33%");
progressSpy.should.have.been.calledWith("67%");
progressSpy.should.have.been.calledThrice;
});
By default, the promises returned by Chai as Promised's assertions are regular Chai assertion objects, extended with
a single then
method derived from the input promise. To change this behavior, for instance to output a promise with
more useful sugar methods such as are found in most promise libraries, you can override
chaiAsPromised.transferPromiseness
. Here's an example that transfer's Q's finally
and done
methods:
chaiAsPromised.transferPromiseness = function (assertion, promise) {
assertion.then = promise.then.bind(promise); // this is all you get by default
assertion.finally = promise.finally.bind(promise);
assertion.done = promise.done.bind(promise);
};
Another advanced customization hook Chai as Promised allows is if you want to transform the arguments to the asserters, possibly asynchronously. Here is a toy example:
chaiAsPromised.transformAsserterArgs = function (args) {
return args.map(function (x) { return x + 1; });
}
Promise.resolve(2).should.eventually.equal(2); // will now fail!
Promise.resolve(2).should.eventually.equal(3); // will now pass!
The transform can even be asynchronous, returning a promise for an array instead of an array directly. An example
of that might be using Promise.all
so that an array of promises becomes a promise for an array. If you do that,
then you can compare promises against other promises using the asserters:
// This will normally fail, since within() only works on numbers.
Promise.resolve(2).should.eventually.be.within(Promise.resolve(1), Promise.resolve(6));
chaiAsPromised.transformAsserterArgs = function (args) {
return Promise.all(args);
};
// But now it will pass, since we transformed the array of promises for numbers into
// (a promise for) an array of numbers
Promise.resolve(2).should.eventually.be.within(Promise.resolve(1), Promise.resolve(6));
Chai as Promised is compatible with all promises following the Promises/A+ specification. Notably, jQuery's
so-called “promises” are not up to spec, and Chai as Promised will not work with them. In particular, Chai as Promised
makes extensive use of the standard transformation behavior of then
, which jQuery does not support.
Some test runners (e.g. Jasmine, QUnit, or tap/tape) do not have the ability to use the returned promise to signal
asynchronous test completion. If possible, I'd recommend switching to ones that do, such as Mocha,
Buster, or blue-tape. But if that's not an option, Chai as Promised still has you covered. As
long as your test framework takes a callback indicating when the asynchronous test run is over, Chai as Promised can
adapt to that situation with its notify
method, like so:
it("should be fulfilled", function (done) {
promise.should.be.fulfilled.and.notify(done);
});
it("should be rejected", function (done) {
otherPromise.should.be.rejected.and.notify(done);
});
In these examples, if the conditions are not met, the test runner will receive an error of the form "expected promise to be fulfilled but it was rejected with [Error: error message]"
, or "expected promise to be rejected but it was fulfilled."
There's another form of notify
which is useful in certain situations, like doing assertions after a promise is
complete. For example:
it("should change the state", function (done) {
otherState.should.equal("before");
promise.should.be.fulfilled.then(function () {
otherState.should.equal("after");
}).should.notify(done);
});
Notice how .notify(done)
is hanging directly off of .should
, instead of appearing after a promise assertion. This
indicates to Chai as Promised that it should pass fulfillment or rejection directly through to the testing framework.
Thus, the above code will fail with a Chai as Promised error ("expected promise to be fulfilled…"
) if promise
is
rejected, but will fail with a simple Chai error (expected "before" to equal "after"
) if otherState
does not change.
Another example of where this can be useful is when performing assertions on multiple promises:
it("should all be well", function (done) {
Q.all([
promiseA.should.become("happy"),
promiseB.should.eventually.have.property("fun times"),
promiseC.should.be.rejectedWith(TypeError, "only joyful types are allowed")
]).should.notify(done);
});
This will pass any failures of the individual promise assertions up to the test framework, instead of wrapping them in
an "expected promise to be fulfilled…"
message as would happen if you did
Q.all([…]).should.be.fulfilled.and.notify(done)
.
Do an npm install chai-as-promised
to get up and running. Then:
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
You can of course put this code in a common test fixture file; for an example using Mocha, see the Chai as Promised tests themselves.
Chai as Promised supports being used as an AMD module, registering itself anonymously (just like Chai). So,
assuming you have configured your loader to map the Chai and Chai as Promised files to the respective module IDs
"chai"
and "chai-as-promised"
, you can use them as follows:
define(function (require, exports, module) {
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
});
<script>
tagIf you include Chai as Promised directly with a <script>
tag, after the one for Chai itself, then it will
automatically plug in to Chai and be ready for use:
<script src="chai.js"></script>
<script src="chai-as-promised.js"></script>
Chai as Promised is only compatible with modern browsers (IE ≥9, Safari ≥6, no PhantomJS).
FAQs
Extends Chai with assertions about promises.
The npm package chai-as-promised receives a total of 1,190,062 weekly downloads. As such, chai-as-promised popularity was classified as popular.
We found that chai-as-promised demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.